<script setup>
import { ref, reactive, onMounted } from 'vue'

const userInfo = ref(null)
const familyMembers = ref([])
const maxMembers = ref(3)
const isPremium = ref(false)
const showUpgradePrompt = ref(false)
const showAddMemberForm = ref(false)

const newMember = reactive({
  fullName: '',
  relationship: '',
  age: '',
  gender: '男',
  phoneNumber: '',
  medicalHistory: ''
})

const genderOptions = ['男', '女']
const relationshipOptions = ['配偶', '子女', '父母', '其他']

onMounted(() => {
  // 获取当前登录用户信息
  const currentUser = uni.getStorageSync('userInfo')
  if (currentUser) {
    userInfo.value = currentUser
    
    // 判断是否是家庭账号
    if (currentUser.accountType !== 'family') {
      uni.showToast({
        title: '非家庭账号无法管理家庭成员',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
      return
    }
    
    // 判断是否是高级会员
    isPremium.value = currentUser.membershipLevel === 'premium'
    
    // 获取家庭成员
    const users = uni.getStorageSync('users') || []
    const currentUserInStorage = users.find(u => u.username === currentUser.username)
    if (currentUserInStorage) {
      familyMembers.value = currentUserInStorage.familyMembers || []
    }
  } else {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/login/index'
      })
    }, 1500)
  }
})

function showAddMember() {
  if (!isPremium.value) {
    showUpgradePrompt.value = true
    return
  }
  
  if (familyMembers.value.length >= maxMembers.value) {
    uni.showToast({
      title: `最多只能添加${maxMembers.value}个家庭成员`,
      icon: 'none'
    })
    return
  }
  
  showAddMemberForm.value = true
}

function hideAddMember() {
  showAddMemberForm.value = false
  // 重置表单
  Object.assign(newMember, {
    fullName: '',
    relationship: '',
    age: '',
    gender: '男',
    phoneNumber: '',
    medicalHistory: ''
  })
}

function addFamilyMember() {
  // 表单验证
  if (!newMember.fullName || !newMember.relationship) {
    uni.showToast({
      title: '请填写必填项',
      icon: 'none'
    })
    return
  }
  
  // 生成唯一ID
  const memberId = Date.now().toString()
  
  // 添加家庭成员
  const memberToAdd = {
    id: memberId,
    fullName: newMember.fullName,
    relationship: newMember.relationship,
    age: newMember.age,
    gender: newMember.gender,
    phoneNumber: newMember.phoneNumber,
    medicalHistory: newMember.medicalHistory,
    addedAt: new Date().getTime()
  }
  
  // 更新本地存储
  const users = uni.getStorageSync('users') || []
  const userIndex = users.findIndex(u => u.username === userInfo.value.username)
  
  if (userIndex !== -1) {
    if (!users[userIndex].familyMembers) {
      users[userIndex].familyMembers = []
    }
    
    users[userIndex].familyMembers.push(memberToAdd)
    users[userIndex].currentMembers = users[userIndex].familyMembers.length
    
    uni.setStorageSync('users', users)
    
    // 更新当前显示的家庭成员列表
    familyMembers.value.push(memberToAdd)
    
    uni.showToast({
      title: '添加成功',
      icon: 'success'
    })
    
    // 隐藏添加表单
    hideAddMember()
  } else {
    uni.showToast({
      title: '用户数据异常',
      icon: 'none'
    })
  }
}

function removeFamilyMember(member) {
  uni.showModal({
    title: '提示',
    content: `确定要移除家庭成员 ${member.fullName} 吗？`,
    success: function(res) {
      if (res.confirm) {
        // 更新本地存储
        const users = uni.getStorageSync('users') || []
        const userIndex = users.findIndex(u => u.username === userInfo.value.username)
        
        if (userIndex !== -1) {
          users[userIndex].familyMembers = users[userIndex].familyMembers.filter(m => m.id !== member.id)
          users[userIndex].currentMembers = users[userIndex].familyMembers.length
          
          uni.setStorageSync('users', users)
          
          // 更新当前显示的家庭成员列表
          familyMembers.value = familyMembers.value.filter(m => m.id !== member.id)
          
          uni.showToast({
            title: '已移除',
            icon: 'success'
          })
        }
      }
    }
  })
}

function goToUpgrade() {
  showUpgradePrompt.value = false
  uni.navigateTo({
    url: '/pages/mine/membership'
  })
}

function closeUpgradePrompt() {
  showUpgradePrompt.value = false
}
</script>

<template>
  <view class="container">
    <view class="header">
      <view class="title">家庭成员管理</view>
      <view class="subtitle">管理您的家庭成员信息</view>
    </view>
    
    <view class="members-container">
      <view class="section-header">
        <text>家庭成员列表</text>
        <text class="count">{{ familyMembers.length }}/{{ maxMembers }}</text>
      </view>
      
      <view v-if="familyMembers.length === 0" class="empty-state">
        <view class="empty-icon">👨‍👩‍👧‍👦</view>
        <view class="empty-text">暂无家庭成员</view>
        <button class="add-btn" @tap="showAddMember">添加家庭成员</button>
      </view>
      
      <view v-else class="members-list">
        <view 
          v-for="member in familyMembers" 
          :key="member.id" 
          class="member-card"
        >
          <view class="member-info">
            <view class="member-header">
              <text class="member-name">{{ member.fullName }}</text>
              <text class="member-relationship">{{ member.relationship }}</text>
            </view>
            <view class="member-details">
              <text>性别: {{ member.gender }}</text>
              <text v-if="member.age">年龄: {{ member.age }}</text>
              <text v-if="member.phoneNumber">电话: {{ member.phoneNumber }}</text>
            </view>
            <view v-if="member.medicalHistory" class="member-medical">
              <text class="medical-label">病史记录:</text>
              <text class="medical-text">{{ member.medicalHistory }}</text>
            </view>
          </view>
          <view class="member-actions">
            <button class="remove-btn" @tap="removeFamilyMember(member)">移除</button>
          </view>
        </view>
        
        <button 
          v-if="familyMembers.length < maxMembers" 
          class="add-btn" 
          @tap="showAddMember"
        >
          添加家庭成员
        </button>
      </view>
    </view>
    
    <!-- 添加家庭成员表单 -->
    <view v-if="showAddMemberForm" class="modal-overlay">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">添加家庭成员</text>
          <text class="modal-close" @tap="hideAddMember">×</text>
        </view>
        
        <view class="form-item">
          <text class="label required">姓名</text>
          <input class="input" v-model="newMember.fullName" placeholder="请输入姓名" />
        </view>
        
        <view class="form-item">
          <text class="label required">关系</text>
          <picker 
            :range="relationshipOptions" 
            @change="e => newMember.relationship = relationshipOptions[e.detail.value]"
          >
            <view class="picker-view">
              <text>{{ newMember.relationship || '请选择' }}</text>
              <text class="picker-arrow">▼</text>
            </view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="label">年龄</text>
          <input class="input" v-model="newMember.age" type="number" placeholder="请输入年龄" />
        </view>
        
        <view class="form-item">
          <text class="label">性别</text>
          <view class="radio-group">
            <view 
              v-for="(item, index) in genderOptions" 
              :key="index"
              class="radio-item"
              :class="{ 'radio-active': newMember.gender === item }"
              @tap="newMember.gender = item"
            >
              <text>{{ item }}</text>
            </view>
          </view>
        </view>
        
        <view class="form-item">
          <text class="label">联系电话</text>
          <input class="input" v-model="newMember.phoneNumber" type="number" placeholder="请输入联系电话" />
        </view>
        
        <view class="form-item">
          <text class="label">既往病史</text>
          <textarea class="textarea" v-model="newMember.medicalHistory" placeholder="请输入既往病史（选填）" />
        </view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @tap="hideAddMember">取消</button>
          <button class="confirm-btn" @tap="addFamilyMember">添加</button>
        </view>
      </view>
    </view>
    
    <!-- 会员升级提示 -->
    <view v-if="showUpgradePrompt" class="modal-overlay">
      <view class="modal-content upgrade-modal">
        <view class="modal-header">
          <text class="modal-title">提示</text>
          <text class="modal-close" @tap="closeUpgradePrompt">×</text>
        </view>
        
        <view class="upgrade-content">
          <text class="upgrade-title">需要高级会员</text>
          <text class="upgrade-desc">您需要升级为高级会员才能添加家庭成员</text>
        </view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @tap="closeUpgradePrompt">取消</button>
          <button class="confirm-btn" @tap="goToUpgrade">升级会员</button>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  margin-bottom: 40rpx;
  
  .title {
    font-size: 40rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }
  
  .subtitle {
    font-size: 28rpx;
    color: #666;
  }
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  
  .count {
    font-weight: normal;
    color: #666;
    font-size: 26rpx;
  }
}

.members-container {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx 30rpx;
  margin-bottom: 40rpx;
}

.empty-state {
  padding: 60rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  
  .empty-icon {
    font-size: 80rpx;
    margin-bottom: 20rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 40rpx;
  }
}

.members-list {
  padding: 10rpx 0;
  
  .member-card {
    padding: 30rpx;
    background-color: #f9f9f9;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    display: flex;
    justify-content: space-between;
    
    .member-info {
      flex: 1;
      
      .member-header {
        display: flex;
        align-items: center;
        margin-bottom: 15rpx;
        
        .member-name {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          margin-right: 20rpx;
        }
        
        .member-relationship {
          font-size: 24rpx;
          color: #fff;
          background-color: #1890ff;
          padding: 4rpx 16rpx;
          border-radius: 20rpx;
        }
      }
      
      .member-details {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 10rpx;
        
        text {
          margin-right: 20rpx;
        }
      }
      
      .member-medical {
        font-size: 26rpx;
        display: flex;
        
        .medical-label {
          color: #333;
          margin-right: 10rpx;
        }
        
        .medical-text {
          color: #666;
          flex: 1;
        }
      }
    }
    
    .member-actions {
      display: flex;
      align-items: center;
      
      .remove-btn {
        font-size: 24rpx;
        color: #ff4d4f;
        background-color: transparent;
        border: 1px solid #ff4d4f;
        border-radius: 30rpx;
        padding: 6rpx 20rpx;
        line-height: 1.5;
        height: 50rpx;
      }
    }
  }
}

.add-btn {
  width: 100%;
  height: 80rpx;
  background-color: #1890ff;
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  margin-top: 20rpx;
}

.required::after {
  content: '*';
  color: #ff4d4f;
  margin-left: 5rpx;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  width: 85%;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  max-height: 80vh;
  overflow-y: auto;
  
  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #eee;
    padding-bottom: 20rpx;
    margin-bottom: 30rpx;
    
    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .modal-close {
      font-size: 40rpx;
      color: #999;
      padding: 0 10rpx;
    }
  }
  
  .modal-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 40rpx;
    
    button {
      width: 180rpx;
      height: 70rpx;
      border-radius: 35rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      &.cancel-btn {
        background-color: #f5f5f5;
        color: #666;
        margin-right: 20rpx;
      }
      
      &.confirm-btn {
        background-color: #1890ff;
        color: #fff;
      }
    }
  }
}

.upgrade-modal {
  .upgrade-content {
    padding: 30rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .upgrade-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 15rpx;
    }
    
    .upgrade-desc {
      font-size: 28rpx;
      color: #666;
      text-align: center;
    }
  }
}

.form-item {
  margin-bottom: 30rpx;
  
  .label {
    display: block;
    font-size: 28rpx;
    color: #333;
    margin-bottom: 15rpx;
  }
  
  .input {
    width: 100%;
    height: 80rpx;
    border: 1px solid #ddd;
    border-radius: 8rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    box-sizing: border-box;
  }
  
  .textarea {
    width: 100%;
    height: 200rpx;
    border: 1px solid #ddd;
    border-radius: 8rpx;
    padding: 20rpx;
    font-size: 28rpx;
    box-sizing: border-box;
  }
  
  .picker-view {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 80rpx;
    border: 1px solid #ddd;
    border-radius: 8rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    box-sizing: border-box;
    
    .picker-arrow {
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .radio-group {
    display: flex;
    
    .radio-item {
      padding: 15rpx 40rpx;
      border: 1px solid #ddd;
      border-radius: 8rpx;
      margin-right: 20rpx;
      font-size: 28rpx;
      
      &.radio-active {
        background-color: #e6f7ff;
        border-color: #1890ff;
        color: #1890ff;
      }
    }
  }
}
</style> 